<template>
  <div
    v-if="viewMode === 'edit'"
    style="display: flex; justify-content: space-around; gap: 24px"
  >
    <a-input :disabled="true" v-model:value="address">
      <template #addonAfter v-if="!disabled">
        <EnvironmentFilled style="color: #0960bd" @click="open" /> </template
    ></a-input>
  </div>
  <div v-else>{{ address }}</div>
  <BasicModal
    v-bind="$attrs"
    width="50%"
    title="选取地址"
    default-fullscreen
    @register="registerModal"
    @ok="submit"
  >
    <a-input-search
      v-model:value="searchPoi"
      placeholder="查找地点"
      style="width: 300px"
      allowClear
      @search="onSearch"
    />
    <div ref="container" style="height: 100%"></div>
  </BasicModal>
</template>
<script setup>
import { ref, unref, watch } from 'vue';
import { EnvironmentFilled } from '@ant-design/icons-vue';
import { BasicModal, useModal } from '/@/components/Modal';
import AMapLoader from '@amap/amap-jsapi-loader';
import setting from '/@/settings/projectSetting';
const props = defineProps({
  value: {
    type: String,
  },
  viewMode: {
    type: String,
  },
  title: {
    type: Object,
  },
  width: {
    type: String,
    default: '50%',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  height: {
    type: String,
    default: '70vh',
  },

  // 初始化的中心点
  center: {
    type: Array,
    default: () => [],
  },
  // 初始化的坐标
  poi: {
    type: Array,
  },
});
const emit = defineEmits(['submit', 'update:value']);
const mapInstance = ref();
const searchPoi = ref('');
const marker = ref();
const address = ref('');
const pos = ref('');
const container = ref();
let onSearch;
const [registerModal, { openModal, closeModal }] = useModal();
watch(
  () => props.value,
  (v) => {
    address.value = v;
  },
);
// 触发父组件赋值
const setValue = () => {
  emit('update:value', address.value);
  emit('change', address.value);
  emit('submit', { address: address.value, position: pos.value.toString() });

};

const initMap = () => {
  AMapLoader.load({
    key: setting.mapKey,
    version: '2.0',
    plugins: ['AMap.Geocoder', 'AMap.PlaceSearch'],
  })
    .then((AMap) => {
      mapInstance.value = new AMap.Map(container.value, {
        zoom: 12,
        zooms: [2, 22],
        // center: props.center || [],
      });
      if (props.poi) {
        addMarker(props.poi);
      }
      // 添加坐标标记点
      const addMarker = (position) => {
        if (unref(marker)) {
          marker.value.remove();
        }
        pos.value = position;
        getAddress(position, (labelContent) => {
          marker.value = new AMap.Marker({
            position,
            label: {
              content: labelContent,
            },
            icon: new AMap.Icon({
              image:
                '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
              size: new AMap.Size(20, 28),
              imageSize: new AMap.Size(20, 28),
            }),
            offset: new AMap.Pixel(0, 0),
            anchor: 'bottom-center',
          });
          marker.value.setMap(mapInstance.value);
          setValue();
        });
      };
      mapInstance.value.on('click', (e) => {
        const { lat, lng } = e.lnglat;
        addMarker([lng, lat]);
      });

      const geocoder = new AMap.Geocoder();
      // 逆地址解析
      const getAddress = (lnglat, callback) => {
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            address.value = result.regeocode.formattedAddress;
            callback(address.value);
          } else {
            address.value = '';
            callback('根据经纬度查询地址失败');
          }
          setValue();
        });
      };
      //构造地点查询类
      const placeSearch = new AMap.PlaceSearch({
        map: mapInstance.value,
      });
      onSearch = (keyword) => {
        placeSearch.search(keyword);
      };
    })
    .catch((e) => {
      console.log(e);
    });
};

const open = () => {
  openModal(true);
  if (!mapInstance.value) {
    setTimeout(() => {
      initMap();
    });
  }
};

// 确定提交
const submit = () => {
  setValue();
  closeModal();
};
</script>
<style>
#container {
  height: 100%;
}
</style>
